<?php
/**
 * @Author: gan
 * @Description: 聚合短信
 * @File:  AliyunSms
 * @Version: 1.0.0
 * @Date: 2021/12/27 9:15 上午
 */
declare(strict_types=1);

namespace RX\Component\Sms\Impl;

use RX\Enums\SmsEnum;
use RX\Exception\BizException;
use RX\Helpers\StringHelper;
use RX\Traits\CurlTrait;

class JuheImpl implements SmsInterface
{
    use CurlTrait;

    private string $key;
    private string $url = "https://v.juhe.cn/sms/send";

    public function __construct(array $config = [])
    {
        if (empty($config)) {
            $config = StringHelper::config('sms.juhe');
        }
        $this->key = $config["key"];
    }

    public function send(string $mobile, string $sign, string $template, array $templateParams = [])
    {
        $params = array(
            'key'    => $this->key,
            'mobile' => $mobile,
            'tpl_id' => $template,
            'vars'   => json_encode($templateParams)
        );
        $result = $this->postCurl($this->url, $params, false);
        $result = json_decode($result, true);
        if (!isset($result['error_code']) || $result['error_code'] != 0) {
            $msg = $result['reason'] ?? null;
            throw new BizException(SmsEnum::class, SmsEnum::SMS_FAIL, $msg);
        }
        return $result;
    }
}
